package com.snail.starter.feign.interceptor;

import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import com.snail.starter.commons.enums.HeaderEnums;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author: snail framework
 * @Date: 2023/2/21 上午9:41
 * @Version: 1.0.0
 */
@Slf4j
@Component
public class BasicFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        UserContext userContext = UserContextUtils.get();
        log.info("BasicFeignInterceptor,serviceName:{},url:{},method:{},body:{},userContext:{}", requestTemplate.feignTarget().name(), requestTemplate.feignTarget().url(), requestTemplate.request().httpMethod().name(), null == requestTemplate.request().body() ? null : new String(requestTemplate.request().body()), userContext);
        try {
            requestTemplate.header(HeaderEnums.TOKEN.getKey(), userContext.getToken());
        } catch (Throwable throwable) {
            log.warn("BasicFeignInterceptor error:{}", userContext);
        }
    }
}
